<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">机器人编号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="id" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">机器人名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">机器人IP</label>
                            <div class="layui-input-inline">
                                <input type="text" name="ip" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">所在区域</label>
                            <div class="layui-input-inline">
                                <input type="text" name="region" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
                <button class="layui-btn layui-btn-sm layui-btn" lay-event="export"> 导出 </button>
                <button class="layui-btn layui-btn-sm layui-btn layui-btn-normal" lay-event="import"> 导入 </button>
						
						
				
               
                <!--<button  class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="import"> 导入 </button>-->
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>
        <script type="text/html" id="ImportExcel">
            <div class="layui-form-block">
                <input type="file" class="layui-btn layui-btn-sm layui-btn-normal" id="LAY-excel-import-excel"
                       multiple="multiple">
            </div>
        </script>
    </div>
</div>

<script>


   
    layui.use(['form', 'table', 'miniPage', 'element', 'excel'], function () {
        var $ = layui.jquery;
        var form = layui.form,
            table = layui.table,
            miniPage = layui.miniPage,
            excel = layui.excel;
        //渲染表格
        table.render({
            elem: '#currentTableId',
            url: 'api/Robot/GetRobotsByPage',
            parseData: function (res) { //res 即为原始返回的数据
                return {

                    "code": res.code === 200 ? 0 : res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.total, //解析数据长度
                    "data": res.data //解析数据列表
                }
            },

            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                { type: "checkbox", width: 50 },
                { field: 'id', width: 100, title: 'ID', sort: true, align: "center" },
                { field: 'name', title: '名称', width: 120, align: "center" },
                { field: 'ip', title: 'IP', sort: true, width: 120, align: "center" },
                { field: 'port', title: 'Port', sort: true, width: 120, align: "center" },
                {
                    field: 'enable', align: "center", width: 120, title: '禁/启用', templet: function (res) {
                        var menuId = res.id;
                        if (res.enable) {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "' lay-filter='state' lay-skin='switch' lay-text='ON|OFF' checked>";
                        } else {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "'  lay-filter='state' lay-skin='switch' lay-text='ON|OFF'>";
                        }
                    }
                },
                { field: 'region', width: 120, title: '所在区域', align: "center" },
                { field: 'payloads', width: 200, title: '可载物料型号', align: "center" },
                { field: 'floor', width: 120, title: '所在楼层', align: "center" },
                {
                    field: 'inElevator', align: "center", width: 200, title: '是/否在电梯里', templet: function (res) {
                        var menuId = res.id;
                        if (res.inElevator) {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "' lay-filter='inElevator' lay-skin='switch' lay-text='ON|OFF' checked>";
                        } else {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "'  lay-filter='inElevator' lay-skin='switch' lay-text='ON|OFF'>";
                        }
                    }
                },
                { title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center" }
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            id: 'reloadTable',
            page: true,
            even: "true",
            skin: 'row',
        });

        //表格重新加载
        var tablereload = function (search) {
            table.reload('reloadTable',
                {
                    where: {
                        query: search
                    }, page: {
                        curr: 1
                    }
                });
        }

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {

            var result = JSON.stringify(data.field);
            console.log(result);
            var query = {};
            for (var key in data.field) {
                if (data.field[key].length > 0) {
                    query[key] = data.field[key];
                }
            }
            console.log(query);
            table.reload('reloadTable', {
                where: {
                    query: JSON.stringify(query)
                }
                , page: {
                    curr: 1
                }
            });

            return false;
        });


        //是否在电梯里
        form.on('switch(inElevator)', function (data) {
            var id = data.elem.attributes['menuId'].nodeValue;
            var inElevator = data.elem.checked;
            var msg = inElevator ? "是" : "否";
            $.ajax({
                url: 'api/Robot/InElevator/' + id + "/" + inElevator,
                method: 'patch',
                contentType: 'application/json',
                cache: false,
                success: function (res) {

                    layer.msg(msg + '成功!', { icon: 1 });
                },
                error: function (data) {

                    layer.msg(msg + '失败!', { icon: 2 });

                }
            });
        });

        //启用和禁用
        form.on('switch(state)', function (data) {

            var id = data.elem.attributes['menuId'].nodeValue;
            var enable = data.elem.checked;
            var msg = enable ? "启用" : "禁用";
            $.ajax({
                url: 'api/Robot/Enable/' + id + "/" + enable,
                method: 'patch',
                contentType: 'application/json',
                cache: false,
                success: function (res) {

                    layer.msg(msg + '成功!', { icon: 1 });
                },
                error: function (data) {

                    layer.msg(msg + '失败!', { icon: 2 });

                }
            });
        });


        //表头添加和删除
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {   // 监听添加操作
                var content = miniPage.getHrefContent('page/AGV/AddAGV.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '添加AGV',
                    type: 1,
                    shade: 0.2,
                    shadeClose: false,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                    //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                    end: function (index, layero) {
                        layer.close(index);
                        //修改成功后刷新父界面
                        tablereload("");
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });


            } else if (obj.event === 'delete') {
                layer.confirm('您确定要删除吗?', function (index) {
                    layer.close(index);
                    // 监听删除操作
                    var checkStatus = table.checkStatus('reloadTable')
                        , data = checkStatus.data;
                    console.log(data);
                    var ids = [];
                    data.forEach(x => { ids.push(x.id); console.log(x.id); });

                    $.ajax({
                        url: 'api/Robot/DeleteByIds',
                        method: 'delete',
                        contentType: 'application/json;charset=UTF-8',
                        cache: false,
                        data: JSON.stringify(ids),
                        success: function (res) {
                            if (res.code === 200) {
                                layer.msg('删除成功!',
                                    { icon: 6 },
                                    function () {
                                        //修改成功后刷新父界面
                                        tablereload("");
                                    });
                            } else
                                alert(res.msg);
                        },
                        error: function (data) {

                            layer.msg('删除失败!');

                        }

                    });
                });

            }
            else if (obj.event === 'export') {

                var data = table.cache.reloadTable
                data = excel.filterExportData(data, [
                    'id'
                    , 'name'
                    , 'ip'
                    , 'port'
                    , 'enable'
                    , 'region'
                    , 'payloads'

                ]);
                data.unshift({ id: "ID", name: "名称", ip: 'IP', port: '端口号', enable: '禁/启用', region: '区域', payloads: '可载物料型号' });
                excel.exportExcel(data, 'AGV信息.xlsx', 'xlsx');
            }
            else if (obj.event === 'import') {
                var index = layer.open({
                    title: '导入数据',
                    type: 1,
                    shade: 0.2,
                   
                    area: ['250px', '180px'],
                    
                    content: $('#ImportExcel').html(),
                    success: function (layero, index) {
                        // 监听上传文件的事件
                        $('#LAY-excel-import-excel').change(function (e) {
                            var files = e.target.files;
                            try {
                                // 方式一：先读取数据，后梳理数据
                                excel.importExcel(files, {}, function (data) {

                                    data = excel.filterImportData(data, {
                                        'id': 'A'
                                        , 'name': 'B'
                                        , 'ip': 'C'
                                        , 'port': 'D'
                                        , 'enable': 'E'
                                        , 'region': 'F'
                                        , 'payloads': 'G'
                                    })
                                   
                                    data = data['0']['sheet1']
                                    data = data.splice(1, data.length - 1)
                                    $.ajax({
                                        url: '/api/Robot/Import',
                                        method: 'post',
                                        contentType: 'application/json',
                                        cache: false,
                                        data: JSON.stringify(data),
                                        success: function (res) {

                                            layer.msg('导入成功!', { icon: 1 });
                                            layer.close(index);
                                        },
                                        error: function (data) {

                                            layer.msg('导入失败!', { icon: 2 });
                                            layer.close(index);

                                        }
                                    });

                                });
                               
                            }
                            catch (e) {
                                layer.alert(e.message);
                            }
                        })

                    },
                    //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                    end: function (index, layero) {
                        layer.close(index);
                        //修改成功后刷新父界面
                        tablereload("");
                    }
                });
            }
        });

       
         //编辑和删除
        table.on('tool(currentTableFilter)', function (obj) {
                    var data = obj.data;
                    console.log(data);
                    if (obj.event === 'edit') {

                        var content = miniPage.getHrefContent('page/AGV/EditAGV.html');
                        var openWH = miniPage.getOpenWidthHeight();

                        var index = layer.open({
                            title: '编辑AGV',
                            type: 1,
                            shade: 0.2,
                            maxmin: true,
                            shadeClose: true,
                            area: [openWH[0] + 'px', openWH[1] + 'px'],
                            offset: [openWH[2] + 'px', openWH[3] + 'px'],
                            content: content,
                            success: function (layero, index) {

                                form.val("editAgvForm",
                                    {
                                        "id": data.id,
                                        "name": data.name,
                                        "ip": data.ip,
                                        "port": data.port,
                                        "payloads": data.payloads,
                                        "region": data.region,
                                        "floor": data.floor
                                    });

                            },
                            //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                            end: function (index, layero) {
                                layer.close(index);
                                //修改成功后刷新父界面
                                tablereload("");
                            }

                        });
                        $(window).on("resize", function () {
                            layer.full(index);

                        });
                        return false;
                    } else if (obj.event === 'delete') {

                        layer.confirm('您确定要删除吗?', function (index) {
                            var id = obj.data.id;

                            obj.del();
                            $.ajax({
                                method: 'delete',
                                contentType: 'application/json;charset=UTF-8',
                                cache: false,
                                url: 'api/Robot/Delete/' + id,
                                success: function (res) {
                                    if (res.code === 200) {
                                        layer.msg('删除成功!');
                                    } else {
                                        layer.msg('删除失败!' + res.message);
                                        tablereload("");
                                    }
                                },
                                error: function (data) {
                                    layer.msg('删除失败!');
                                }
                            });
                            layer.close(index);
                        });
                    }
                });

     });
   
   
</script>